<template>
  <el-drawer
    custom-class="drawer-box"
    v-model="drawerData.show"
    :title="drawerData.title"
    :direction="direction"
    :before-close="handleClose"
    :close-on-click-modal="false"
    size="35%"
  >
    <template #title>
      <span class="drawer-title">{{ drawerData.title }}</span>
    </template>
    <div class="form-box">
      <el-form
        class="ruleFormRef"
        ref="ruleFormRef"
        :model="formData"
        :rules="rules"
        label-width="150px"
      >
        <!-- systemAttrList -->
        <el-form-item
          v-for="item in formAttrList"
          :key="item.code"
          :label="item.attr_name + ':'"
          :prop="item.key"
        >
          <el-input
            v-if="item.attr_type == 'input'"
            v-model="formData[item.key]"
            :placeholder="`请输入客户${item.attr_name}`"
          ></el-input>
          <el-select
            v-else
            style="width: 100%"
            v-model="formData[item.key]"
            :placeholder="`请选择客户${item.attr_name}`"
            :popper-append-to-body="false"
          >
            <el-option
              v-for="it in item.attr_val"
              :key="it.value"
              :label="it.label"
              :value="it.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 动态属性 -->
        <el-form-item
          v-for="item in customAttrList.data"
          :key="item.attr_id"
          :label="item.attr_name"
          :prop="item.prop"
        >
          <el-input
            v-if="
              item.attr_type == 'textbox' || item.attr_type == 'mobile' || item.attr_type == 'email'
            "
            v-model="formData[item.prop]"
            :placeholder="`请输入${item.attr_name}`"
          ></el-input>
          <el-input
            v-model="formData[item.prop]"
            v-if="item.attr_type == 'textarea'"
            type="textarea"
            :placeholder="`请输入${item.attr_name}`"
          ></el-input>
          <!-- 多选 -->

          <el-checkbox-group v-model="formData[item.prop]" v-if="item.attr_type == 'muti_select'">
            <el-checkbox
              v-for="it in item.attr_val"
              :key="it.val"
              :value="it.key"
              :label="it.key"
              >{{ it.val }}</el-checkbox
            >
          </el-checkbox-group>

          <el-radio-group v-model="formData[item.prop]" v-if="item.attr_type == 'select'">
            <el-radio v-for="it in item.attr_val" :key="it.val" :label="it.key">{{
              it.val
            }}</el-radio>
          </el-radio-group>

          <el-date-picker
            v-if="item.attr_type == 'date'"
            v-model="formData[item.prop]"
            type="date"
            :placeholder="`请输入${item.attr_name}`"
          ></el-date-picker>

          <el-cascader
            v-if="item.attr_type == 'pca'"
            v-model="formData[item.prop]"
            :options="item.attr_val"
            :placeholder="`请选填${item.attr_name}`"
          ></el-cascader>
          <!--  -->
          <ZWUpload
            v-if="item.attr_type == 'picture'"
            :upInfo="item.upInfo"
            @submit="getUploadData($event, item.prop)"
          />
          <!-- <el-select
            style="width: 100%"
            v-model="formData[item.key]"
            :placeholder="`请选择客户${item.attr_name}`"
          >
            <el-option
              v-for="it in item.attr_val"
              :key="it.value"
              :label="it.key"
              :value="it.value"
            ></el-option>
          </el-select> -->
        </el-form-item>
      </el-form>
      <div class="btn-box">
        <el-button @click="initFormData">重置</el-button>
        <el-button type="primary" @click="saveFun">保存</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script lang="ts" setup>
  import ZWUpload from '@/components/ZWUpload.vue'
  import { reactive, ref } from '@vue/reactivity'
  import { watch } from '@vue/runtime-core'
  import bus from '@/utils/bus'
  import { ElForm, ElMessage } from 'element-plus'
  import { createCustomer, getAttrList } from '@/api/customerCenter'
  type FormInstance = InstanceType<typeof ElForm>
  const emit = defineEmits(['save'])
  const ruleFormRef: any = ref<FormInstance>()
  const props = defineProps(['sourceArr'])
  let drawerData = ref({
    show: false,
    title: '添加客户',
    direction: 'rtl' //从右往左打开
  })

  let formData: any = ref({})

  let validPhone = (rules: any, value: any, callback: any) => {
    let rex = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    if (!value) {
      callback(new Error('请输入电话号码'))
    } else if (!rex.test(value)) {
      callback(new Error('请输入正确的11位手机号码'))
    } else {
      callback()
    }
  }
  let validEmail = (rules: any, value: any, callback: any) => {
    let rex = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/
    if (!value) {
      callback(new Error('请输入邮箱'))
    } else if (!rex.test(value)) {
      callback(new Error('请输入正确的邮箱'))
    } else {
      callback()
    }
  }

  // 图片上传
  const picInfo = ref({})

  // 重置
  const initFormData = () => {
    ruleFormRef.value?.resetFields()
  }

  // 关闭
  const handleClose = () => {
    drawerData.value.show = false
  }

  const systemAttrList: any = [
    { attr_name: '姓名', attr_type: 'input', attr_val: [], code: 'name', key: 'name' },
    { attr_name: '电话', attr_type: 'input', attr_val: [], code: 'mobile', key: 'mobile' },
    { attr_name: '性别', attr_type: 'select', attr_val: [], code: 'sex', key: 'sex' },
    { attr_name: '邮箱', attr_type: 'input', attr_val: [], code: 'email', key: 'email' },
    { attr_name: '地址', attr_type: 'input', attr_val: [], code: 'address', key: 'address' },
    { attr_name: '公司', attr_type: 'input', attr_val: [], code: 'company', key: 'company' },
    { attr_name: 'QQ', attr_type: 'input', attr_val: [], code: 'qq', key: 'qq_number' },
    { attr_name: '微信号', attr_type: 'input', attr_val: [], code: 'wx', key: 'wx_number' },
    { attr_name: '客户来源', attr_type: 'select', attr_val: [], code: 'source', key: 'source_id' },
    { attr_name: '备注', attr_type: 'input', attr_val: [], code: 'remark', key: 'remark' }
  ]

  let rules: any = ref({
    mobile: { required: true, validator: validPhone, trigger: 'blur' },
    name: { required: true, trigger: 'blur', message: '请输入客户姓名' },
    email: { required: true, trigger: 'blur', validator: validEmail },
    address: { required: true, trigger: 'blur', message: '请选择客户地址' },
    company: { required: true, trigger: 'blur', message: '请选择客户公司' },
    qq_number: { required: true, trigger: 'blur', message: '请选择客户QQ' },
    wx_number: { required: true, trigger: 'blur', message: '请选择客户微信' },
    source_id: { required: true, trigger: 'change', message: '请选择客户来源' },
    sex: { required: true, trigger: 'change', message: '请选择客户性别' }
  })

  // 当前渲染的参数
  let formAttrList: any = ref([])
  let customAttrList: any = reactive({
    data: []
  })

  // 获取创建客户属性列表
  const getAttrListFun = () => {
    getAttrList({})
      .then((r: any) => {
        systemAttrList.forEach((item: any) => {
          let indx = r.system_attr.system_code.findIndex((it: any) => {
            return it == item.code
          })
          if (indx > -1) {
            if (item.code == 'sex') {
              item.attr_val = [
                { label: '男', value: '1' },
                { label: '女', value: '2' },
                { label: '未知', value: '0' }
              ]
            }
            if (item.code == 'source') {
              item.attr_val = props.sourceArr
            }
            formAttrList.value.push(item)
            formData.value[item.key] = ''
          }
        })
        // 动态属性
        r.custom_attr.forEach((item: any) => {
          let key = 'form_attr_' + item.attr_id
          let val: any = ''
          if (
            item.attr_type == 'select' ||
            item.attr_type == 'muti_select' ||
            item.attr_type == 'picture'
          ) {
            val = []
          }
          formData.value[key] = val;
          
          rules.value[key] = { required: true, message: `请选填${item.attr_name}`, trigger: 'blur' };
          if(item.attr_name == '邮箱' || item.attr_name == '电话' || item.attr_name == '手机号'){
            rules.value[key].validator = item.attr_name == '邮箱' ? validEmail : validPhone;
          }
          item.prop = key
          // 如果是上传图片
          if (item.attr_type == 'picture') {
            item.upInfo = {
              type: 1,
              label: '',
              prop: 'images',
              multiple: false,
              limitSize: 2,
              limitNum: 1,
              acceptFile: '.jpg,.jpeg,.png,.gif,.bmp,.webp'
            }
          }
          customAttrList.data.push(item)
        })
      })
      .catch((e: object) => {
        console.log(e, 555)
        ElMessage.error('服务器开小差')
        // handleClose();
      })
  }

  watch(
    () => drawerData.value.show,
    (val: boolean) => {
      if (val) {
        formAttrList.value = []
        customAttrList.data = []
        getAttrListFun()
      }
    }
  )

  // 获取上传的图片
  const getUploadData = (data: any, key: string) => {
    formData.value[key] = data[0] ? data[0].url : ''
  }

  // 保存
  const saveFun = () => {
    ruleFormRef.value.validate((valid: boolean) => {
      if (valid) {
        let {
          name,
          mobile,
          sex,
          email,
          address,
          company,
          qq_number,
          wx_number,
          remark,
          source_id
        } = formData.value
        let param: object = {
          mobile,
          source_id,
          system_attr: {
            name,
            sex,
            email,
            address,
            company,
            qq_number,
            wx_number,
            remark
          },
          custom_attr: []
        }
        customAttrList.data.forEach((item: any) => {
          param.custom_attr.push({
            attr_id: item.attr_id,
            attr_name: item.attr_id,
            attr_type: item.attr_type,
            attr_val: formData.value[item.prop]
          })
        })
        createCustomer(param)
          .then((r: object) => {
            ElMessage.success('客户创建成功')
            handleClose()
            emit('save', true)
          })
          .catch((e: object) => {})
      }
    })
  }

  defineExpose({
    drawerData
  })
</script>

<style lang="scss" scoped>
  .drawer-box {
    .drawer-title {
      color: #333;
      font-weight: bold;
    }
    .form-box {
      max-height: calc(100vh - 126px);
      overflow-y: scroll;
      .ruleFormRef {
        margin-bottom: 40px;
      }
      .btn-box {
        text-align: right;
        border-top: solid 1px #eee;
        padding: 20px;
      }
    }
    .form-box::-webkit-scrollbar {
      display: none;
    }
  }
</style>
